<template>
	<section >
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="loadData" icon="el-icon-search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="handleAdd" icon="fa fa-plus"> 新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pets" :height="450" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="宠物名称" width="160" sortable>
			</el-table-column>
			<el-table-column prop="costprice" label="成本价" width="100" sortable>
			</el-table-column>
			<el-table-column prop="saleprice" label="零售价" width="100" sortable>
			</el-table-column>
			<el-table-column prop="coatColor.name" label="毛色" width="80" sortable>
			</el-table-column>
			<el-table-column prop="petType.name" label="类型" width="80" sortable>
			</el-table-column>
			<el-table-column prop="offsaletime" label="下架时间" width="160" sortable>
			</el-table-column>
			<el-table-column prop="onsaletime" label="上架时间" width="160" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="80"  sortable>
				<template scope="scope">
					<span v-if="scope.row.state == 0" style="color: #11b95c">已上架</span>
					<span v-else style="color:red">已下架</span>
				</template>
			</el-table-column>
			<el-table-column prop="user.username" label="购买人" width="100" sortable>
			</el-table-column>
			<el-table-column label="操作" width="110">
				<template scope="scope">
					<el-button size="small" type="success" circle @click="handleEdit(index,scope.row)" icon="el-icon-edit"></el-button>
					<el-button size="small" type="danger" circle @click="handleDel(scope.row.id)" icon="el-icon-delete"></el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--分页条+ 批量删除-->
		<el-col :span="24" class="toolbar">
			<!--@click="batchRemove"-->
			<el-button type="danger"  :disabled="this.sels.length===0">批量删除</el-button>
			<el-button type="primary" :disabled="this.sels.length===0" v-on:click="handleUp" icon="fa fa-plus"> 批量上架</el-button>
			<el-button type="primary" :disabled="this.sels.length===0" v-on:click="handleDown" icon="fa fa-plus"> 批量下架</el-button>
			<el-pagination layout="total, sizes, prev, pager, next, jumper" @current-change="handleCurrentChange" @size-change="handleSizeChange"
						   :total="total"
						   :current-page="filters.currentPage"
						   :page-size="filters.pageSize"
						   :page-sizes="[5, 10, 20, 50]"
						   style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面
			:rules 申明数据校验规则
		-->
		<el-dialog title="新增/编辑" :visible.sync="petsFormVisible" :close-on-click-modal="false" >
			<el-form :model="petsForm" label-width="80px" :rules="petsFormRules" ref="petsForm">
				<el-row :gutter="10">
					<el-col :span="8">
						<el-form-item label="名称" prop="name">
							<el-input v-model="petsForm.name" size="mini" auto-complete="off"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="成本价" prop="costprice">
							<el-input v-model="petsForm.costprice" size="mini" auto-complete="off"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="零售价" prop="saleprice">
							<el-input v-model="petsForm.saleprice" size="mini" auto-complete="off"></el-input>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="10">
					<el-col :span="8">
						<el-form-item label="宠物类型" prop="petType">
							<el-select v-model="petsForm.petType" placeholder="请选择" value-key="id">
								<el-option
										v-for="item in petTypes"
										:key="item.id"
										:label="item.name"
										:value="item">
									<span style="float: left">{{ item.name }}</span>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="毛色" prop="SystemDictionaryDetail">
							<el-select v-model="petsForm.coatColor" placeholder="请选择" value-key="id">
								<el-option
										v-for="item in coatColors"
										:key="item.id"
										:label="item.name"
										:value="item">
									<span style="float: left">{{ item.name }}</span>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
					</el-col>
				</el-row>

				<el-form-item label="资源" prop="resources">
					<el-upload
							class="upload-demo"
							action="http://localhost:8080/fastdfs/upload"
							:on-remove="handleRemove"
							:on-success="handleSuccess"
							:file-list="fileList"
							list-type="picture">
						<el-button size="small" type="primary">点击上传</el-button>
						<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
					</el-upload>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="petsFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="submitForm" :loading="shopLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
    import 'quill/dist/quill.core.css';
    import 'quill/dist/quill.snow.css';
    import 'quill/dist/quill.bubble.css';
    import quillConfig from '../../common/js/quill-config';
	export default {
		data() {
			return {
                quillConfig:quillConfig,	//自定义组件属性
				filters: {
                    keyword: '',
                    currentPage: 1,
					pageSize: 10
				},
                total: 0,
				pets: [],
                petTypes:[],
                coatColors:[],
				listLoading: false,
				sels: [],//列表选中列
                fileList:[],		//文件上传的列表
				productResource: [],	//商品图片路径数组
				petsFormVisible: false,//弹出框界面是否显示
				shopLoading: false,//忙等框
				petsFormRules: {//绑定表单校验规则
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//编辑界面数据
				petsForm: {
					id: null,
					name: '',
					resources: '',
                    state: 0,	//0下架
                    saleprice:'',
					costprice:'',
                    shop_id:null,
                    petType:null,   //宠物类型
                    coatColor:null //毛发颜色
				}
			}
		},
		methods: {
            //切换当前显示多少条数据
            handleSizeChange(val) {
                this.filters.pageSize = val;
                this.loadData();
            },
            //切换当前页码
			handleCurrentChange(val) {
				this.filters.currentPage = val;
				this.loadData();
			},
			//获取宠物列表
			loadData() {
                let userJson = localStorage.getItem("userJsonStr");
                let loginUser = JSON.parse(userJson);
                console.debug(loginUser.shop.id);
				let para = {
                    currentPage: this.filters.currentPage,
                    keyword: this.filters.keyword,
                    pageSize:this.filters.pageSize,
					shop_id:loginUser.shop.id
				};
				this.listLoading = true;
				//NProgress.start();
				this.$http.post("/pet",para).then(result => {
					this.listLoading = false;
					result = result.data;//直接抽取了一层
					this.total = result.totals;
					this.pets = result.rows;
				}).catch(result=>{
					alert("系统错误！！！");
					this.listLoading = false;
				})
			},
			//显示新增界面
            handleAdd(){
                this.petsFormVisible = true;//弹出编辑框
				//重置表单
                this.petsForm = {
                    id: null,
                    name: '',
                    resources: '',
                    state: -1,
                    costprice:'',
                    saleprice:'',
                    salecount: 0,
                    productDetail:{
                        intro:'',
                        orderNotice:''
                    }
                };
                //清空fileList
                this.fileList = []
			},
			//显示编辑界面
            handleEdit: function (index,row) {
                //先清空fileList
                this.fileList = [];
				//先重置表单
                this.petsForm = {
                    id: null,
                    name: '',
                    resources: '',
                    state: 0,	//0下架
                    saleprice:'',
                    costprice:'',
                    shop_id:null,
                    user_id:null,
                    type_id:null
                };
                this.petsFormVisible = true;//弹出编辑框
				//Object.assign  克隆数据
				this.petsForm = Object.assign({}, row);//数据回显
                //回填el-upload组件的图片
                //先以逗号分隔字符串
                let imgUrls = row.resources.split(",");
                for(let i=0;i<imgUrls.length;i++){
                    //获取图片名称：最后一个斜杠后面的内容
                    let name = imgUrls[i].substring(imgUrls[i].lastIndexOf("/") + 1);
					let url = "http://121.37.194.36" + imgUrls[i];
					this.fileList.push({
						name,
						url
					})
				}
			},
			//提交表单
			submitForm: function () {
			    //表单验证
			    this.$refs.petsForm.validate( r => {
			        if(r){
                        this.shopLoading = true;  //开启 正在加载
                        //NProgress.start();
						this.$http.put('/pet', this.petsForm).then(res => {
                            this.shopLoading = false;		//关闭 正在加载
						    let {success,message} = res.data;
							if(success){
						        this.$message.success(message);
                                this.petsFormVisible = false;	//关闭模态框
								//重新加载表格数据
								this.filters.currentPage = 1;
                                this.loadData();
							}else{
						        this.$message.error(message)
							}
						})
					}
				})
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//文件上传成功
            handleSuccess(response, file, fileList){
			    this.productResource.push(response.data);
				this.petsForm.resources = this.productResource.join(",");
				console.debug(this.petsForm.resources)
			},
			//点击删除已上传到fastdfs的文件
			handleRemove(file, fileList){
                console.log(arr[1],filename);
                /*let para = {
                    "group":arr[1],
                    "filename":filename
                };
                this.$http.delete("/fastdfs/delete",para)
                    .then(res=>{
                        if(res.data.success){
                            this.$message({
                                message: '删除成功!',
                                type: 'success'
                            });
                        }else{
                            this.$message({
                                message: '删除失败!',
                                type: 'error'
                            });
                        }
                    })*/

			},
            selsChange: function (sels) {
                this.sels = sels;
            },
            //删除
            handleDel: function (id) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    this.$http.delete("/pet/"+id)
                        .then(result=>{
                            this.listLoading = false;
                            result = result.data;//直接抽取了一层
                            if(result.success){//true
                                this.page = 1;
                                this.$message({
                                    message: result.message,
                                    type: 'success'
                                });
                            }else{//false
                                this.$message({
                                    message: result.message,
                                    type: 'error'
                                });
                            }
                            this.loadData();
                        })
                        .catch(result=>{

                        })
                }).catch(() => {

                });
            },
            //宠物上架
            handleUp(){
                var ids = this.sels.map(item => item.id);
                this.$http.patch("/pet/up",ids).then(res=>{
                    let {success,message} = res.data;
                    if(success){
                        //将当前页切换至第一页
                        this.filters.currentPage = 1;
                        this.loadData();
                        this.$message.success('上架成功')
					}else {
                        this.$message.error(message)
					}
				})
			},
			//宠物下架
            handleDown(){
                var ids = this.sels.map(item => item.id);
                this.$http.patch("/pet/down",ids).then(res=>{
                    let {success,message} = res.data;
                    if(success){
                        //将当前页切换至第一页
                        this.filters.currentPage = 1;
                        this.loadData();
                        this.$message.success('下架成功')
                    }else {
                        this.$message.error('下架失败')
                    }
                })
			},
			//下拉列表获取所有宠物类型
			loadpetType(){
                this.$http.get("/pet/types").then(res=>{
                    this.petTypes = res.data;
				})
			},
			//下拉列表获取所有宠物毛色
            loadcoatColors(){
                this.$http.get("/systemDictionaryDetail/coat_color").then(res=>{
                    this.coatColors = res.data;
                })
            }
		},
		mounted() {
			this.loadData();
			this.loadpetType();
			this.loadcoatColors();
		}
	}

</script>

<!--
	scoped ：作用域
-->
<style>
	.el-dialog{width: 70%;}
	.ql-editor{height: 100px!important;}
</style>